#include <cmath>
#include <sys/time.h>
#include "core.h"
#include "time.h"


namespace {
    int _frames = 0;
    double _last_frame = 0;
    double _this_frame = 0;
    
    double _current_time();
    double _current_time() {
        struct timeval time_now;
        gettimeofday(&time_now, NULL);
        return time_now.tv_sec + time_now.tv_usec * 0.000001;
    }
    double _framerate = 10.0;
    int _last_framerate = 0;
    double _last_framerate_sampled = 0;
}

namespace gametime {

int FrameCount() {
    return _frames;
}

double Wave(double period) {
    double t = fmod(GlobalTime(), period) / period;
    return cos(t * CONST_TWOPI);
}
double Wave2(double period) {
    double r = Wave(period);
    return pow(fabs(r), 0.8) * (r >= 0 ? 1 : -1);
}

void Tick() {
    _last_frame = _this_frame;
    _this_frame = _current_time();
    _frames += 1;
    double gt = GlobalTime();
    if (_last_framerate == 0) {
        _last_framerate = FrameCount();
        _last_framerate_sampled = gt;
    } else if (gt > _last_framerate_sampled + 1.0) {
        _framerate = (FrameCount() - _last_framerate) / (gt - _last_framerate_sampled);
        _last_framerate_sampled = gt;
        _last_framerate = FrameCount();
    }
}

double FrameRate() {
    return _framerate;
}
    
double dt() {
    return _this_frame - _last_frame;
}

double GlobalTime() {
    return _this_frame;
}

void Init() {
    _this_frame = _current_time();
    _last_frame = _this_frame - 0.05;
}

}  // namespace gametime
